package com.laijiale.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.laijiale.constant.ML;
import com.laijiale.dto.SeckillInsertDTO;
import com.laijiale.dto.SeckillPageDTO;
import com.laijiale.dto.SeckillUpdateDTO;
import com.laijiale.entity.Article;
import com.laijiale.entity.Seckill;
import com.laijiale.exception.ServiceException;
import com.laijiale.result.Result;
import com.laijiale.until.MinioUtil;
import com.laijiale.vo.SeckillSimpleListVO;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.laijiale.entity.Seckill;
import com.laijiale.mapper.SeckillMapper;
import com.laijiale.service.SeckillService;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

import static com.laijiale.entity.table.SeckillTableDef.SECKILL;
import static com.laijiale.entity.table.EpisodeTableDef.EPISODE;
import static com.laijiale.entity.table.SeasonTableDef.SEASON;
import static com.laijiale.entity.table.UserTableDef.USER;
import static com.mybatisflex.core.query.QueryMethods.*;

/**
 * 秒杀表 服务层实现。
 *
 * @author laijiale
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "seckill")
public class SeckillServiceImpl extends ServiceImpl<SeckillMapper, Seckill>  implements SeckillService{
    LocalDateTime nowTime=LocalDateTime.now();
    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(SeckillInsertDTO dto) {
        // 判断生效时间和失效时间是否合理
        if (dto.getStartTime().isAfter(dto.getEndTime())) {
            throw new ServiceException("生效时间不能在失效时间之后");
        }
        // 判断生效时间和失效时间是否合理
        if (dto.getStartTime().isAfter(LocalDateTime.now())){
            throw new ServiceException("生效时间不能在当前时间之后");
        }
        // 判断生效时间和失效时间是否合理
        if (dto.getEndTime().isBefore(LocalDateTime.now())){
            throw new ServiceException("失效时间不能在当前时间之前");
        }
        //标题查重
        if(QueryChain.of(mapper).where(SECKILL.TITLE.eq(dto.getTitle())).exists()){
            throw new ServiceException("秒杀标题已存在") ;
        }
        //组装entity实体类
        Seckill seckill= BeanUtil.copyProperties(dto,Seckill.class);

        if (seckill.getInfo()==null){
            seckill.setInfo("无详细信息");
        }
        seckill.setStatus(ML.Seckill.NOT_START);
        seckill.setCreated(LocalDateTime.now());
        seckill.setUpdated(LocalDateTime.now());
        return mapper.insert(seckill)>0;

    }

    @Cacheable(key = "#p0",condition = "#p0 !=null",unless = "#result ==null")
    @Override
    public Seckill select(Long id) {
        return mapper.selectOneWithRelationsById(id);
    }

    @Override
    public List<Seckill> top(Long N) {
        List<Seckill> seckills= QueryChain.of(mapper)
               .where(dateDiff(currentDate(), dateFormat(SECKILL.START_TIME, "%Y-%m-%d")).eq(0))
                                .orderBy(SECKILL.START_TIME.asc()).limit(N).list();

        return seckills;
    }

    @Cacheable(key = "#root.methodName",
            unless = "#result == null"
    )
    @Override
    public List<SeckillSimpleListVO> simpleList() {
        List<SeckillSimpleListVO> seckillSimpleListVOS=QueryChain.of(mapper).listAs(SeckillSimpleListVO.class);
        return seckillSimpleListVOS;
    }

    @Cacheable(key = "#root.methodName + ':' + #p0.toString()",
            condition ="#p0 != null",
            unless = "#result == null")
    @Override
    public Page<Seckill> page(SeckillPageDTO dto) {

        QueryChain<Seckill> queryChain = QueryChain.of(mapper);

        // title 条件
        String title = dto.getTitle();
        if(ObjectUtil.isNotNull(title)) {
            queryChain.where(SECKILL.TITLE.like(title));
        }
        return queryChain.withRelations().page(new Page<>(dto.getPageNum(), dto.getPageSize()));
    }


    @CacheEvict(allEntries = true)
    @Override
    public boolean update(SeckillUpdateDTO dto) {

        // 标题查重
        if (QueryChain.of(mapper).
                where(SECKILL.TITLE.eq(dto.getTitle()))
                .and(SECKILL.ID.ne(dto.getId()))
                .exists()) {
            throw new ServiceException("秒杀标题已存在");
        }

        // 组装 entity 实体类
        Seckill seckill = BeanUtil.copyProperties(dto, Seckill.class);
        // 设置 entity 默认值
        seckill.setUpdated(LocalDateTime.now());
        return UpdateChain.of(seckill).where(SECKILL.ID.eq(seckill.getId())).update();
    }
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {
        return mapper.deleteById(id) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {
        return mapper.deleteBatchByIds(ids) > 0;
    }



}
